/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年5月30日
 */
package com.massyframework.beanskin.runtime.framework.installing;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.massyframework.beanskin.ModuleIdentifier;
import com.massyframework.beanskin.ParseException;
import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.framework.Framework;
import com.massyframework.beanskin.initparam.InitParameters;
import com.massyframework.beanskin.initparam.SubsetParameters;
import com.massyframework.beanskin.util.BeanSkinServiceLoaderUtils;
import com.massyframework.beanskin.util.IOUtils;
import com.massyframework.beanskin.util.localstore.LocalStore;
import com.massyframework.beanskin.util.variables.StringVariableReplacer;

/**
 * 抽象的模块解析器
 * @author huangkh
 *
 */
public abstract class AbstractModuleParser<B> implements ModuleParser<B> {
	
	protected static final String PREFIX         = "#{";
	protected static final String SUBFIX         = "}";
	
	private Validator validator;
	private Assembly kernel;
	private LocalStore localStore;
	private ModuleIdentifier identifier;
	
	/**
	 * 构造方法
	 * @param kernel {@link Assembly},内核装配件
	 */
	public AbstractModuleParser(Assembly kernel, LocalStore localStore) {
		this.kernel = Objects.requireNonNull(kernel, "\"kernel\" cannot be null.");
		this.localStore = Objects.requireNonNull(localStore, "\"localStore\" cannot be null.");
	}
		
	@Override
	public B parse(ModuleIdentifier identifier, File xmlFile) throws SAXException, ParseException, IOException {
		this.validateXml(xmlFile);
		
		this.identifier = identifier;
		B result = this.createBuilder();
		if (result == null) {
			throw new RuntimeException("cannot create " + this.getBuilderType() + " instance.");
		}
		
		InputStream is = null;
		try {			
			is = new FileInputStream(xmlFile);
			Document document = this.createDocument(is);
			this.doParse(document, result);
		}finally {
			IOUtils.close(is);
		}
		return result;
	}
	
	/**
	 * 创建构建器
	 * @return
	 */
	protected B createBuilder() {
		return BeanSkinServiceLoaderUtils.loadService(this.getBuilderType(), this.getClass().getClassLoader());
	}
	
	/**
	 * 创建表达式
	 * @param builder {@link B}
	 * @return {@link Expression}
	 */
	protected Expression<String> createExpression(B builder, StringVariableReplacer replacer){
		ExpressionFactory factory = new ExpressionFactory(this.getKernel());
		Expression<String> result = factory.createExpression(String.class);
		
		String groupId = this.getModuleIdentifier().getGroupId();
		String moduleId = this.getModuleIdentifier().getModuleId();
		String version = this.getModuleIdentifier().getVersion().toString();
		String identifier = this.getModuleIdentifier().toIdentifier();
		
		result.setVariable("groupId", groupId);
		result.setVariable("moduleId", moduleId);
		result.setVariable("version", version);
		result.setVariable("identifier", identifier);
		
		Map<String, String> variables = new HashMap<>();
		variables.put("groupId", groupId);
		variables.put("moduleId", moduleId);
		variables.put("version", version);
		variables.put("identifier", this.getModuleIdentifier().toIdentifier());
		replacer.addVariables(variables);
		
		String any = "module.*.";
		Map<String, String> anyParams = this.getSubParams(this.getKernel().getConfig(), any);
		if (!anyParams.isEmpty()) {
			for (Map.Entry<String, String> entry: anyParams.entrySet()) {
				result.setVariable(entry.getKey(), entry.getValue());
			}
			replacer.addVariables(anyParams);
		}				
		return result;
	}
	
	/**
	 * 根据前缀取回对应的Map
	 * 
	 * @param initParams {@link InitParameters},初始化参数
	 * @param prefix     {@link String},前缀
	 * @return {@link Map}
	 */
	protected Map<String, String> getSubParams(InitParameters initParams, String prefix) {
		Map<String, String> result = new HashMap<>();
		SubsetParameters sub = new SubsetParameters(initParams, prefix);

		List<String> names = sub.getParameterNames();
		for (String name : names) {
			result.put(name, sub.getParameter(name));
		}
		return result;
	}

	/**
     * 获取下级子节点， elementName构成的列表
     * @param node {@link Node}
     * @param elementName {@link String}, 元素名称
     * @return {@link List}
     */
    protected List<String> getChildNodeValue(Node node, String elementName){
        List<String> result = new ArrayList<>();

        NodeList nodes = node.getChildNodes();
        int size = nodes.getLength();
        for (int i=0; i<size; i++){
            Node childNode = nodes.item(i);
            if (childNode.getNodeName().equals(elementName)){
                String text = this.getTextContent(childNode);
                if (text != null) {
                    result.add(text);
                }
            }
        }

        return result;
    }
    
    /**
     * 获取下级子节点， elementName构成的列表
     * @param node {@link Node}
     * @param elementName {@link String}, 元素名称
     * @return {@link List}
     */
    protected List<String> getChildNodeValue(Node node, String elementName, Function<String, String> expressionFun){
        List<String> result = new ArrayList<>();

        NodeList nodes = node.getChildNodes();
        int size = nodes.getLength();
        for (int i=0; i<size; i++){
            Node childNode = nodes.item(i);
            if (childNode.getNodeName().equals(elementName)){
                String text = this.findAndReplace(this.getTextContent(childNode), expressionFun);
                if (text != null) {
                    result.add(text);
                }
            }
        }

        return result;
    }
	
	/**
     * 获取节点的TextContent数据
     * @param node 节点
     * @return {@link String}, 可以返回null.
     */
    public String getTextContent(Node node){
        if (node == null) return null;

        String result = node.getTextContent();
        if (result == null){
            return null;
        }

        result = StringUtils.trim(result);
        if (result.isEmpty()){
            return null;
        }

        return result;
    }
    
    /**
    *
    * @param value {@link String}, 可能包含表达式的值
    * @param expressionFun {@link Function}, 表达式取值函数， 可能为null.
    * @return {@link String}, 表达式的值
    */
    protected String findAndReplace(String value, Function<String, String> expressionFun){
       if (StringUtils.isEmpty(value)) return null;
       if (expressionFun == null) return value;

       String result = StringUtils.indexOf(value,"${") != -1 ?
               expressionFun.apply(value):
               value;

       return StringUtils.isEmpty(result) ? null : result;
   }

    /**
     * 验证 xml文件的有效性
     * @param xmlFile {@link File}, xml文件
     * @throws SAXException xml解析发生例外
     * @throws IOException io读写发生例外
     */
    protected void validateXml(File xmlFile) throws SAXException, IOException{
        InputStream inputStream = null;
        try{
            inputStream = new FileInputStream(xmlFile);
            StreamSource source = new StreamSource(inputStream);
            this.getValidator().validate(source);
        }finally{
            if (inputStream != null) {
                try {
                    inputStream.close();
                }catch(IOException e) {

                }
            }
        }
    }
    
    /**
     * 创建Xml Document对象
     * @param inputStream 输入流
     * @return {@link Document}
     * @throws ParseException 解析发生错误抛出的异常
     * @throws IOException IO读写发生异常抛出的异常
     * @throws SAXException SAX解析发生错误抛出的异常
     */
    protected final Document createDocument(InputStream inputStream)
            throws ParseException, IOException {
        try{
            DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
            DocumentBuilder builder=factory.newDocumentBuilder();
            return builder.parse(inputStream);
        }catch(ParserConfigurationException e){
            throw new ParseException("load assmebly configuration file failed.", e);
        }catch(SAXException e){
            throw new ParseException("load assmebly configuration file failed.", e);
        }catch(IOException e){
            throw e;
        }
    }

	/**
     * 创建验证器
     * @param xsdResource {@link String},验证所使用的xsd文件路经
     * @return {@link Validator}
     * @throws SAXException
     */
    protected Validator getValidator() throws SAXException {
    	if (this.validator == null) {
	    	ClassLoader loader = Framework.class.getClassLoader();
	    	
	    	String resourceName = this.getResouceNameWithXmlSchemaFile();
	    	URL url =  loader.getResource(resourceName);
	    	if (url == null) {
	    		throw new RuntimeException("cannot found xsd resource:".concat(resourceName).concat("."));
	    	}
	    	
	        SchemaFactory schemaFactory =
	                SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
	
	        Schema schema = schemaFactory.newSchema(url);
	        this.validator = schema.newValidator();
    	}
    	
    	return this.validator;
    }
    
    /**
     * 内核装配件
     * @return {@link Assembly}
     */
    public Assembly getKernel() {
    	return this.kernel;
    }
    
    /**
     * 本地存储
     * @return
     */
    public LocalStore getLocalStore() {
    	return this.localStore;
    }
        
    /**
     * 模块标识符
     * @return {@link ModuleIdentifier}
     */
    public ModuleIdentifier getModuleIdentifier() {
    	return this.identifier;
    }
    
    /**
     * 执行文档解析
     * @param doc {@link Document}, xml文档
     * @param builder  {@link B},构建器实例
     * @return {@link Expression}
     */
    protected abstract void doParse(Document doc, B builder);
    	
	/**
	 * xml Schema文件路径
	 * @return {@link String}
	 */
	protected abstract String getResouceNameWithXmlSchemaFile();
	
	/**
	 * 获取构建器类型
	 * @return {@link Class}
	 */
	protected abstract Class<B> getBuilderType();
}
